import {
	BASE_URL
} from '@/config.js'

// 预设宽高指标
const width = 750;
const height = 750;

const waterfall = async (obj = { hs: [0, 0], list: [], key: 'imgUrl' }, fn, showProgress = false) => {
	let { hs, list, key } = obj
	let [leftH, rightH] = hs
	let formatList = [[], []];
	let selfList = []
	for (let i = 0, len = list.length; i < len; i++) {
		let item = list[i][key] || ''
		let url = item.split(',')[0] || ''
		url = url.split('&cover=')[1] || url
		await new Promise(resolve => {
			let el = null
			uni.getImageInfo({
				src: BASE_URL + url,
				success: res => {
					selfList.push([i, width * (res.height / res.width)])
				},
				fail: e => {
					selfList.push([i, height])
				},
				complete: () => {
					resolve(1)
				}
			})
		})
	}
	selfList = selfList.sort((a, b) => a[1] -b[1])
	selfList.map(([index, h]) => {
		// 限制最高600
		h = h > 600 ? 600 : h
		if (leftH <= rightH) {
			leftH+=h
			formatList[0].push(list[index])
		} else {
			rightH+=h
			formatList[1].push(list[index])
		}
	})
	fn([leftH, rightH], formatList)
}

export default waterfall
